import { createRouter, createWebHistory } from 'vue-router';
import { UserRoleEnum } from '@/enums/UserRoleEnum';
import { routes } from '@/router/routes';
import { userLoginUserStore } from '@/stores/loginUser';
import {checkAuthorization} from '@/utils/authorization';

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes: routes
});

router.beforeEach(async (to,
						 from,
						 next) => {

	if (to.name === 'login') {
		next();
		return;
	}
	// 获取当前登录用户	}
	// 获取当前登录用户
	const loginUserStore = userLoginUserStore();
	let loginUser = loginUserStore.loginUser;
	if (!loginUserStore.isLogin()) {
		await loginUserStore.login();
	}
	loginUser = loginUserStore.loginUser;

	// 获取当前页面需要的访问权限
	const access = to.meta?.roleNeed ?? UserRoleEnum.ANONYMOUS;
	// 判断该用户是否需要登录
	if (access !== UserRoleEnum.ANONYMOUS) {
		// 判断该用户是否登录
		if (loginUserStore.isLogin()) {
			if (!checkAuthorization(loginUser, access)) {
				next(`/no-authority`);
			}
		} else {
			next(`/login`);
			return;
		}
	}
	next();
});

export default router;
